﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using lruc.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace lruc.Controllers
{
    public class AdminController : BaseController
    {
        public AdminController(IFreeSql fsql) : base(fsql)
        {
        }

        [HttpGet]
        public async Task<IDictionary<string, Object>> List()
        {
            List<User> users = await _fsql.Select<User>().ToListAsync();
            return RenderJson(data: users);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Save([FromForm] User user)
        {
            string status = "failed";
            string message = "该用户已存在";
            int code = -1;
            // 判断用户是否存在
            User isExistsUser = await _fsql.Select<User>().Where(u => u.Username == user.Username).ToOneAsync();
            if (isExistsUser == null)
            {
                long id = await _fsql.Insert(user).ExecuteIdentityAsync();
                user.Id = id;
                status = "success";
                message = "添加用户成功";
                code = 0;
            }
            return RenderJson(status: status, message: message, code: code, data: user);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Delete([FromForm] long id) {
            User user = await _fsql.Select<User>().Where(u => u.Id == id).ToOneAsync();
            if (user.Username.Equals("admin")) {
                return RenderJson(status: "failed", message: "管理员无法删除", code: -1, data: user);
            }
            int affrows = await _fsql.Delete<User>().Where(u => u.Id == id).ExecuteAffrowsAsync();
            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Update([FromForm] User user) {
            int affrows = await _fsql.Update<User>().SetSourceIgnore(user, colval => colval == null).ExecuteAffrowsAsync();
            return RenderJson(data: affrows);
        }

        [HttpGet]
        public async Task<IDictionary<string, Object>> Show([FromQuery] long id) {
            User user = await _fsql.Select<User>().Where(u => u.Id == id).ToOneAsync();
            return RenderJson(data: user);
        }
    }
}
